package com.bj58.data.emailreports.controllers;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bj58.data.emailreports.model.CPCHour;
import com.bj58.data.emailreports.service.CPCOpenHourService;
import com.bj58.data.emailreports.utils.DateUtil;
import com.bj58.data.emailreports.utils.EmailReportUtil;
import com.bj58.data.emailreports.utils.MailUtil;
import com.bj58.data.emailreports.utils.ResourcesUtil;
import com.bj58.data.emailreports.utils.SomePublicUtil;
import com.bj58.data.emailreports.utils.SortUtil;
import com.bj58.data.emailreports.utils.SubmitSms;
import com.bj58.data.emailreports.utils.VelocityTools;
import com.bj58.groupbuy.service.locator.ServiceLocator;
import com.bj58.groupbuy.util.PathUtil;
import com.bj58.data.emailreports.dao.CommonDao;
import com.bj58.data.emailreports.dao.SrcDbPool.DBType;

/**
 * CPC监控日报，每小时数据
 * @author zhaoxiang
 *
 */
public class CPCOpenHourController {
	private VelocityTools vTools = new VelocityTools();
	private SomePublicUtil spu = new SomePublicUtil();
	private CPCOpenHourService cpcOpenService= ServiceLocator.get(CPCOpenHourService.class);
	
	private static CommonDao comDao = new CommonDao();
	
	/**
	 * CPC每小时数据监控日报
	 */
	public String cpcOpenHourReport(String searchDate,int hour)throws Exception{
			//读取模板内容
			String filepath = PathUtil.getWFNamespaceFolder()+"/emailtemp/CPCOpenHour.html";
			String templateContext = ResourcesUtil.getTemByPath(filepath);
			//渲染MAP
			Map<String,Object> conMap = new HashMap<String,Object>();
			
			//查询日期
			String beginTime = DateUtil.getStringDate(DateUtil.strToDate(hour+":00", "HH:mm"), "HH:mm");
			String endTime = DateUtil.getStringDate(DateUtil.strToDate((hour+1)+":00", "HH:mm"), "HH:mm");
			conMap.put("beginTime", beginTime);
			conMap.put("endTime", endTime);
			String today = searchDate;//今日
			String yesterday = DateUtil.strToStrBefore(searchDate, "yyyy-MM-dd", 1);//昨日
			String lastWeek = DateUtil.strToStrBefore(searchDate, "yyyy-MM-dd", 7);//上周
			conMap.put("nowDate",today.substring(today.indexOf("-")+1).replace("-", "."));
			conMap.put("lastDate",yesterday.substring(yesterday.indexOf("-")+1).replace("-", "."));
			conMap.put("lastWeek",lastWeek.substring(lastWeek.indexOf("-")+1).replace("-", "."));
			
			Map<String,String> dateMap = new HashMap<String, String>();
			dateMap.put("nowDate",today);
			dateMap.put("lastDate", yesterday);
			dateMap.put("lastWeek",lastWeek);
			List<String> dateList = new ArrayList<String>();
			dateList.add(today);dateList.add(yesterday);dateList.add(lastWeek);
			
			double threshold = 0.9;
			double threshold1 = 0.8; //设置两个阈值，如50%，+-0.3，表示有50%的同环比超过阈值0.3
			EmailReportUtil eru = new EmailReportUtil();
			
			//截止当前总体数据
			List<CPCHour> totalList = cpcOpenService.getTotalData(hour,today,yesterday,lastWeek,"");
			List<String>  wholeDicsList = spu.getECDicByAnnotation(CPCHour.class);
			List<String> allDataList = eru.conDataTypeOneWithWarn(totalList, CPCHour.class, null, dateMap, "statDate",wholeDicsList,threshold1);
			conMap.put("totalList",allDataList);
			
			//分时段数据
			String cols1[]={"amount","cashAmount","click","cusCount","units","accountHitCus","budgetHitCus","accountWillHitCus","budgetWillHitCus"};
			List<String> showCols=Arrays.asList(cols1);
			List<CPCHour> hourList = cpcOpenService.getHourData(hour,today,yesterday,lastWeek,"");
			List<String> hourData = eru.conDataTypeFourWithWarn(hourList, CPCHour.class, "cate", showCols, "statDate", null, dateList,threshold1);
			List<String> finalData = sortByHour(hourData);
			conMap.put("hourData",finalData);
			
			//分类别分时段数据
			String[] cates={"黄页","招商加盟","招聘","房产","二手创新","二手推广","二手车"};
			List<String> cateList = Arrays.asList(cates);
			List<String> showCateList = new ArrayList<String>(cateList);
			Map<String,List<CPCHour>> cateMap = new HashMap<String,List<CPCHour>>();
			Map<String,List<String>> cateDataMap = new HashMap<String,List<String>>();
			
			List<CPCHour> cateHourList = cpcOpenService.getCateHourData(hour,today,yesterday,lastWeek,"");
			
			for(CPCHour tmp : cateHourList){ //分类
				List<CPCHour> li = cateMap.get(tmp.getCate());
				if(li == null)
					li = new ArrayList<CPCHour>();
				li.add(tmp);
				cateMap.put(tmp.getCate(),li);
			}
			
			for(String cate:showCateList){
				List<CPCHour> tmpList = cateMap.get(cate);
				if(tmpList == null){
					showCateList.remove(cate);
					continue;
				}
				List<String> rowData = eru.conDataTypeFourWithWarn(tmpList, CPCHour.class, "hour", showCols, "statDate", null, dateList,threshold1);
				rowData = sortByHour(rowData);
				cateDataMap.put(cate, rowData);
			}
			
			conMap.put("cateList",showCateList);
			conMap.put("cateDataMap",cateDataMap);
			
			//分类别截止当前数据
			List<CPCHour> cateTotallist = cpcOpenService.getCateTotalData(hour,today,yesterday,lastWeek,"");
			List<String> cateTotalData = eru.conDataTypeFourWithWarn(cateTotallist, CPCHour.class, "cate", showCols, "statDate", null, dateList,threshold1);
			conMap.put("cateTotalData",SortUtil.sortListByFileName(cateTotalData,1,2));
			
			String[] titles={"消费","现金消费","点击","客户数","推广单元数","余额撞线客户数","预算撞线客户数","余额预撞线客户数","预算预撞线客户数"};
			conMap.put("titles", titles);
			String finalContent = VelocityTools.render(templateContext, conMap);
			//阈值预警
			if(eru.getAbnomalTd()*1.0/eru.getTd() > threshold){
				String head = "当前阈值:"+vTools.tranRateTwo(threshold)+",+-"+threshold1+"<br>";
				head += "异常数据比例:"+vTools.compRateDirect(eru.getAbnomalTd(),eru.getTd())+"<br>";
				MailUtil.javaMailSend("【预警】CPC每小时数据监控日报" +searchDate +" "+beginTime+"--"+endTime, head+finalContent, "zhaoxiang@58.com;huangliang@58.com",null);
				Map<String,String> sendMap = new HashMap<String, String>();
	        	sendMap.put("13522482231", "【预警】CPC每小时数据监控日报" +searchDate +" "+beginTime+"--"+endTime);
//	        	sendMap.put("13811583416",【预警】CPC每小时数据监控日报" +searchDate +" "+beginTime+"--"+endTime);
	        	SubmitSms.submitMsg(sendMap);
				return "";
			}
			return finalContent;
	}
	
	public List<String> sortByHour(List<String> hourData) throws Exception{
		hourData=SortUtil.sortListByFileName(hourData,0,1);
		List<String> finalData = new ArrayList<String>();
		for(String line: hourData){
			int index = line.indexOf(";");
			String h = line.substring(0,index);
			String rowdata = line.substring(index);
			String begin = DateUtil.getStringDate(DateUtil.strToDate(h+":00", "HH:mm"), "HH:mm");
			String end = DateUtil.getStringDate(DateUtil.strToDate((Integer.parseInt(h)+1)+":00", "HH:mm"), "HH:mm");
			String rowHead = begin+"--"+end;
			finalData.add(rowHead+rowdata);
		}
		return finalData;
	}
	
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		
//		System.out.println(Integer.parseInt("05"));
		CPCOpenHourController cpcOpen = new CPCOpenHourController();
		String date= DateUtil.getStringDate(new Date(),"yyyy-MM-dd");
		int hour = Integer.parseInt(DateUtil.getStringDate(new Date(), "HH"));
		if(hour == 0){
			hour = 23;
			date = DateUtil.strToStrBefore(date, "yyyy-MM-dd", 1);
		}else{
			hour =hour - 2; //两小时前
		}
		date="2016-03-01";
		hour=7;
		
		long maxWait = 30*60*1000; //最多等30分钟
		while(maxWait > 0){
			System.out.println("begin check source table :"+date+","+hour);
			
			String month = date.substring(0,date.lastIndexOf("-")).replace("-", "");
			String sql="select count(1) from data_bi.t_jingzhun_user_click_aduserantispam_hour_"+month +" where stat_date ='"+date+"' and stat_hour = "+hour ;
			
			int count = comDao.countAll(sql,DBType.db_131_data_bi.getValue());
			if(count > 0){
				System.out.println("source table has "+count+" recodes!");
				break;
			}
			System.out.println("source table is not ready then sleep for 1 minites!");
			maxWait -= 60*1000;
			Thread.sleep(60*1000);
		}
		if(maxWait<=0)
		{
			System.exit(0);
		}
		
		String beginTime = DateUtil.getStringDate(DateUtil.strToDate(hour+":00", "HH:mm"), "HH:mm");
		String endTime = DateUtil.getStringDate(DateUtil.strToDate((hour+1)+":00", "HH:mm"), "HH:mm");
		String content = cpcOpen.cpcOpenHourReport(date,hour);
		if(!"".equals(content)){
			MailUtil.javaMailSend("CPC每小时数据监控日报测试" +date +" "+beginTime+"--"+endTime, content, "guoxue@58.com",null);
		}
	}

	private static void exit(int i) {
		// TODO Auto-generated method stub
		
	}

}
